<template>
  <div class="news-list">
    <n-card>
      <template #header>
        <div class="header-actions">
          <span>{{ t('menu.newsList') }}</span>
          <div style="display: flex; align-items: center; gap: 8px;">
            <n-button size="small" quaternary @click="resetColumnWidths">
              <template #icon>
                <n-icon><Icons name="refresh-outline" /></n-icon>
              </template>
              重置列宽
            </n-button>
            <n-button type="primary" @click="handleAdd">
              <template #icon>
                <n-icon><AddOutline /></n-icon>
              </template>
              {{ t('news.addNews') }}
            </n-button>
          </div>
        </div>
      </template>

      <div class="search-form">
        <n-form inline :model="searchForm" :show-label="false">
          <n-form-item>
            <n-input
              v-model:value="searchForm.title"
              :placeholder="t('news.title')"
              clearable
            />
          </n-form-item>
          <n-form-item>
            <n-select
              v-model:value="searchForm.status"
              :placeholder="t('common.status')"
              clearable
              :options="statusOptions"
              style="width: 120px"
            />
          </n-form-item>
          <n-form-item>
            <n-button type="primary" @click="handleSearch">
              {{ t('common.search') }}
            </n-button>
            <n-button @click="handleReset" style="margin-left: 8px">
              {{ t('common.reset') }}
            </n-button>
          </n-form-item>
        </n-form>
      </div>

      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :scroll-x="1200"
        :class="{ 'resizing': isResizing }"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
        remote
      />
    </n-card>

    <n-modal v-model:show="showModal" preset="dialog" :title="modalTitle">
      <div v-if="modalType === 'view'" class="news-detail">
        <div class="detail-item">
          <label>标题:</label>
          <span>{{ currentNews.title }}</span>
        </div>
        <div class="detail-item">
          <label>创作者:</label>
          <span>{{ currentNews.creator_name }}</span>
        </div>
        <div class="detail-item">
          <label>状态:</label>
          <span>{{ getStatusText(currentNews.status) }}</span>
        </div>
        <div class="detail-item">
          <label>创建时间:</label>
          <span>{{ formatDate(currentNews.created_at) }}</span>
        </div>
        <div class="detail-item">
          <label>发布时间:</label>
          <span>{{ currentNews.published_at ? formatDate(currentNews.published_at) : '未发布' }}</span>
        </div>
        <div class="detail-item">
          <label>统计数据:</label>
          <p>浏览量: {{ currentNews.view_count }} | 点赞数: {{ currentNews.like_count }} | 评论数: {{ currentNews.comment_count }}</p>
        </div>
        <div class="detail-item" v-if="currentNews.review_reason">
          <label>审核意见:</label>
          <span>{{ currentNews.review_reason }}</span>
        </div>
        <div class="detail-item">
          <label>内容:</label>
          <RichViewer :value="currentNews.content" />
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useResizableColumns } from '@/composables/useResizableColumns'
import {
  NCard,
  NButton,
  NIcon,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NDataTable,
  NTag,
  NModal,
  useMessage,
  useDialog
} from 'naive-ui'
import { AddOutline, EyeOutline, CreateOutline, TrashOutline } from '@/components/Icons'
import Icons from '@/components/Icons.vue'
import RichViewer from '@/components/RichViewer.vue'
import { newsApi } from '@/api'
import type { NewsItem } from '@/api'

const router = useRouter()
const { t } = useI18n({ useScope: 'global' })
const message = useMessage()
const dialog = useDialog()

const loading = ref(false)
const showModal = ref(false)
const modalType = ref<'view' | 'edit'>('view')
const currentNews = ref<any>({})

const searchForm = reactive({
  title: '',
  status: null
})

const tableData = ref<NewsItem[]>([])
const pagination = reactive({
  page: 1,
  pageSize: 5,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [5, 10, 20, 50],
  showQuickJumper: true,
  prefix: ({ itemCount }: any) => `共 ${itemCount} 条`
})

const modalTitle = computed(() => {
  return modalType.value === 'view' ? t('common.view') : t('news.editNews')
})

const statusOptions = computed(() => [
  { label: '审核中', value: 0 },
  { label: '已发布', value: 1 },
  { label: '审核不通过', value: -1 }
])

const getStatusTag = (status: number) => {
  const tagProps: any = { size: 'small' }
  let statusText = ''
  
  switch (status) {
    case 1:
      tagProps.type = 'success'
      statusText = '已发布'
      break
    case 0:
      tagProps.type = 'warning'
      statusText = '审核中'
      break
    case -1:
      tagProps.type = 'error'
      statusText = '审核不通过'
      break
    default:
      tagProps.type = 'default'
      statusText = '未知'
  }
  return h(NTag, tagProps, () => statusText)
}

// 基础列配置
const baseColumns = [
  {
    title: 'ID',
    key: 'id',
    width: 60,
    minWidth: 50,
    maxWidth: 100
  },
  {
    title: '标题',
    key: 'title',
    width: 200,
    minWidth: 150,
    maxWidth: 300,
    ellipsis: { tooltip: true }
  },
  {
    title: '创作者',
    key: 'creator_name',
    width: 100,
    minWidth: 80,
    maxWidth: 150
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    minWidth: 80,
    maxWidth: 120,
    render: (row: any) => getStatusTag(row.status)
  },
  {
    title: '浏览量',
    key: 'view_count',
    width: 80,
    minWidth: 60,
    maxWidth: 120
  },
  {
    title: '点赞数',
    key: 'like_count',
    width: 80,
    minWidth: 60,
    maxWidth: 120
  },
  {
    title: '评论数',
    key: 'comment_count',
    width: 80,
    minWidth: 60,
    maxWidth: 120
  },
  {
    title: '创建时间',
    key: 'created_at',
    width: 160,
    minWidth: 120,
    maxWidth: 200,
    render: (row: any) => {
      // 格式化时间显示
      return new Date(row.created_at).toLocaleString('zh-CN')
    }
  },
  {
    title: '发布时间',
    key: 'published_at',
    width: 160,
    minWidth: 120,
    maxWidth: 200,
    render: (row: any) => {
      // 格式化时间显示，如果未发布则显示空
      return row.published_at ? new Date(row.published_at).toLocaleString('zh-CN') : '-'
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    minWidth: 180,
    maxWidth: 250,
    resizable: false,
    render: (row: any) => {
      const buttons = [
        h(NButton, {
          size: 'small',
          onClick: () => handleView(row)
        }, { default: () => '查看', icon: () => h(NIcon, () => h(EyeOutline)) }),
        
        h(NButton, {
          size: 'small',
          type: 'primary',
          onClick: () => handleEdit(row),
          style: { marginLeft: '8px' }
        }, { default: () => '编辑', icon: () => h(NIcon, () => h(CreateOutline)) }),
        
        h(NButton, {
          size: 'small',
          type: 'error',
          onClick: () => handleDelete(row),
          style: { marginLeft: '8px' }
        }, { default: () => '删除', icon: () => h(NIcon, () => h(TrashOutline)) })
      ]
      
      return h('div', buttons)
    }
  }
]

// 使用可调整列宽的Hook
const { resizableColumns, resetColumnWidths, isResizing } = useResizableColumns({
  columns: baseColumns,
  tableKey: 'news-list',
  defaultWidths: {
    'id': 60,
    'title': 200,
    'creator_name': 100,
    'status': 100,
    'view_count': 80,
    'like_count': 80,
    'comment_count': 80,
    'created_at': 160,
    'published_at': 160,
    'actions': 200
  }
})

const columns = computed(() => resizableColumns.value)

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '审核中'
    case 1: return '已发布'
    case -1: return '审核不通过'
    default: return '未知'
  }
}

const loadData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page - 1, // API页码从0开始，前端从1开始
      rows: pagination.pageSize,
      ...searchForm
    }
    
    const response = await newsApi.getList(params)
    
    if (response.code === 200 && response.status === 'success' && response.data) {
      tableData.value = response.data.news_list || []
      pagination.itemCount = response.data.total || 0
    } else {
      message.error('加载数据失败')
    }
  } catch (error: any) {
    console.error('加载数据错误:', error)
    if (error.status !== 401) {
      message.error(error.error || '加载数据失败')
    }
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  searchForm.title = ''
  searchForm.status = null
  pagination.page = 1
  loadData()
}

const handlePageChange = (page: number) => {
  console.log('页码变化:', { from: pagination.page, to: page, willSendToAPI: page - 1 })
  pagination.page = page
  loadData()
}

const handlePageSizeChange = (pageSize: number) => {
  console.log('每页条数变化:', { from: pagination.pageSize, to: pageSize })
  pagination.pageSize = pageSize
  pagination.page = 1 // 重置到第一页
  loadData()
}

const handleAdd = () => {
  router.push('/news/edit')
}

const handleView = async (row: any) => {
  try {
    loading.value = true
    const response = await newsApi.getDetail(row.id)
    
    if (response.code === 200 && response.status === 'success' && response.data) {
      currentNews.value = response.data.news
      modalType.value = 'view'
      showModal.value = true
    } else {
      message.error('获取新闻详情失败')
    }
  } catch (error: any) {
    console.error('获取新闻详情错误:', error)
    if (error.status !== 401) {
      message.error(error.error || '获取新闻详情失败')
    }
  } finally {
    loading.value = false
  }
}

const handleEdit = (row: any) => {
  router.push(`/news/edit/${row.id}`)
}

const handleDelete = (row: any) => {
  dialog.warning({
    title: t('common.confirm'),
    content: `确认删除新闻"${row.title}"吗？`,
    positiveText: t('common.confirm'),
    negativeText: t('common.cancel'),
    onPositiveClick: async () => {
      try {
        await newsApi.delete(row.id)
        message.success('删除成功')
        loadData()
      } catch (error) {
        message.error('删除失败')
      }
    }
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 16px;
}

.news-detail {
  padding: 16px;
}

.detail-item {
  margin-bottom: 16px;
}

.detail-item label {
  font-weight: bold;
  margin-right: 8px;
}

.content-html {
  border: 1px solid #e0e0e0;
  padding: 16px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}
</style>
